package com.example.lib.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.widget.LinearLayout
import com.example.lib.R
import com.example.lib.databinding.ViewTopImageBottomTextBinding
import com.example.lib.extend.gone
import com.example.lib.extend.isVisi
import com.example.lib.extend.visi
import androidx.core.content.withStyledAttributes

class TopImageBottomTextView @JvmOverloads constructor(context: Context,
    attributes: AttributeSet? = null,
    style: Int = 0) : LinearLayout(context, attributes, style) {
    var binding: ViewTopImageBottomTextBinding
    private var isGone = false
    private var isOffline = true

    init {
        val view = inflate(getContext(), R.layout.view_top_image_bottom_text, this)
        binding = ViewTopImageBottomTextBinding.bind(view)
        context.withStyledAttributes(attributes, R.styleable.TopImageBottomTextView) {
            gravity = Gravity.CENTER
            orientation = VERTICAL
            val topImage = getResourceId(R.styleable.TopImageBottomTextView_topImage, 0)
            val title = getString(R.styleable.TopImageBottomTextView_titleText)
            val color = getColor(R.styleable.TopImageBottomTextView_text_color, Color.BLACK)
            isGone = getBoolean(R.styleable.TopImageBottomTextView_isGone, false)
            if (topImage != 0) binding.ViewImage.setImageResource(topImage)
            if (title != null) binding.ViewText.text = title
            binding.ViewText.setTextColor(color)

            binding.ViewImage.isVisi(isGone.not())
            binding.ViewText.isVisi(isGone.not())
        }
    }

    fun on(image: Int, color: Int = R.color.blue_4279ff) {
        isOffline = false
        binding.ViewImage.setImageResource(image)
        binding.ViewText.setTextColor(context.getColor(color))
        checkEnable()
    }

    fun off(image: Int, color: Int = R.color.black_76) {
        isOffline = true
        binding.ViewImage.setImageResource(image)
        binding.ViewText.setTextColor(context.getColor(color))
        checkEnable()
    }

    fun setTitleText(title: String) {
        binding.ViewText.text = title
    }

    fun visibleLayout() {
        isGone = false
        binding.ViewImage.visi()
        binding.ViewText.visi()
        checkEnable()
    }

    fun goneLayout() {
        isGone = true
        binding.ViewImage.gone()
        binding.ViewText.gone()
        checkEnable()
    }

    private fun checkEnable() {
        isEnabled = isGone.not() && isOffline.not()
    }
}